package com.yc.thread.lock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.LockSupport;

public class TestLockSupport {
	
	private int a = 100;
	Thread t1 = null;//线程1：增加
	Thread t2 = null;//线程1：减少
	
	/**
	 * 不加锁
	 */
	public void m1() {
		//增加
		t1 = new Thread(() -> {
			for (int i = 0; i < 100; i++) {
				a++;
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
		//减少
		t2 = new Thread(() -> {
			for (int i = 0; i < 100; i++) {
				a--;
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
		t1.start();
		t2.start();
		try {
			t1.join();
			t2.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		System.out.println(a);//预期：0   实际：不确定
		
	}
	
	//1. 输出1,2,3.。。
	//2. 输出a,b,c...
	
	Object obj1 = new Object();
//	Object obj2 = new Object();
	
	List<String> charList = new ArrayList<String>(52);//字母集合
	
	public void setCharList() {
		for (int i = 65; i < 91; i++) {
			charList.add((char)i + "");
		}
		for (int i = 97; i < 123; i++) {
			charList.add((char)i + "");
		}
	}
	
	
	Object key = new Object();
	/**
	 * 交替输出1a2b3c。。。
	 * 点：线程异步变逻辑同步，使用线程通讯
	 */
	public void m2() {
		//输出52个数字
		t1 = new Thread(() -> {
			for (int i = 0; i < 52; i++) {
				System.out.println(i+1);
				LockSupport.unpark(t2);//解锁t2
				LockSupport.park();//阻塞当前线程(这个要放在后面，否则就停在这句话这里，就无法解锁t2)
			}
		});
		
		//输出a~z  A~Z
		setCharList();//加载52个字母
		t2 = new Thread(() -> {
			LockSupport.park(key);//先阻塞当前线程(不能放在for循环里，因为不是for循环的逻辑)
			for (int i = 0; i < charList.size(); i++) {
				System.out.println(charList.get(i));
				LockSupport.unpark(t1);//解锁t1
				if (i != (charList.size()-1)) {//完善逻辑：最后一个输出的是z，然后线程不能再阻塞
					LockSupport.park();//阻塞当前线程(这个要放在后面，否则就停在这句话这里，就无法解锁t1)
				}
				
			}
		});
		
		t1.start();
		t2.start();
		
	}
	

	public static void main(String[] args) {
		TestLockSupport ts = new TestLockSupport();
//		ts.m1();
		ts.m2();

	}

}
